package pl.us.ij.plugins.segmentation.commands.filters;

import ij.process.FloatProcessor;
import pl.us.ij.plugins.segmentation.Trace;
import pl.us.ij.plugins.segmentation.infrastructure.Command;

import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User: Przemek
 * Date: 2010-01-08
 * Time: 00:19:12
 * To change this template use File | Settings | File Templates.
 */
public class MedianFilterCommand extends Command<MedianFilterCommandParams> {

//    @Override
    protected void processImage(FloatProcessor fp) {

        int maskSize = getParams().getMaskSize();
        int width = fp.getWidth();
        int height = fp.getHeight();

        int iterationCount = getParams().getIterationCount();

        while (iterationCount-- > 0) {

            float[] pixels = (float[]) fp.getPixelsCopy();

            Trace.log("M:" + pixels[0] + ", " + pixels[1] + ", " + pixels[2] + ", " + pixels[3] + ", " + pixels[4]);
            Trace.log("Min:" + fp.getMin());
            Trace.log("Max:" + fp.getMax());

            float[] outPixels = (float[]) fp.getPixels();
            float[] colors = new float[maskSize * maskSize];
            int[] shifts = new int[maskSize];

            for (int y = maskSize / 2; y < height - maskSize / 2; y++) {
                for (int k = 0; k < maskSize; k++) {
                    shifts[k] = (y + (k - maskSize / 2)) * width;
                }
                int shiftD = y * width;

                for (int x = 0; x < width - maskSize + 1; x++) {
                    for (int maskRow = 0; maskRow < maskSize; maskRow++)
                        System.arraycopy(pixels, shifts[maskRow] + x, colors, maskRow * maskSize, maskSize);

                    int blackCount = 0;
                    for (int i = 0; i < maskSize * maskSize; i++) {
                        if (colors[i] == 0)
                            blackCount++;
                    }

                    if (!getParams().isBlack() && !getParams().isWhite()) {
                        Arrays.sort(colors);
                        outPixels[shiftD + x + maskSize / 2] = colors[maskSize * maskSize / 2];
                    } else if (blackCount <= maskSize * maskSize / 2) {
                        if (getParams().isBlack()) {
                            outPixels[shiftD + x + maskSize / 2] = 0;
                        }
                    } else {
                        if (getParams().isWhite()) {
                            outPixels[shiftD + x + maskSize / 2] = 255;
                        }
                    }
                }
            }

//            fp.setPixels(outPixels);
        }
    }

//    @Override
    protected void process(FloatProcessor fp) {

        processImage(fp);
    }
}
